
from flask import Flask, url_for, request, render_template, redirect, escape,\
    session, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:////tmp/test.db', convert_unicode = True)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

app = Flask(__name__)


@app.route('/_add_numbers')
def add_numbers():
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)
    f = open('/Users/jiangzhenfeng/PycharmProjects/flaskTest/hello.py', 'r')
    str = f.readlines()
    f.close()
    return jsonify(result = a+b, other_str=str)
    # return jsonify(result = a+b)


@app.route('/')
def index():
    return 'First Page\n Hello!'

@app.route('/sesson_test')
def sesson_test():
    if 'username' in session:
        return

@app.route('/login/',methods=['POST','GET'])
def login():
    error=None
    if request.method == 'POST':
        if valid_login(request.form['username'],request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
            return render_template('hello.html',name=error)
    elif request.method == 'GET':
        print('GET login')
        if valid_login(request.values['username'],request.values['password']):
            return log_the_user_in(request.values['username'])
        else:
            error = 'Invalid username/password'
            return render_template('hello.html',name=error)


@app.route('/user/<username>')
def profile(username):
    return 'User is %s' % username


@app.route('/static/')
def static_file():
    return 'please input file name'


@app.route('/user/<username>/')
def show_user_profile(username):
    return 'User is %s' % username


@app.route('/post/<int:post_id>/')
def show_post(post_id):
    return 'Post is %d' % post_id


@app.route('/<int:city_id>/<int:user_id>/')
def show_city_user_id(city_id, user_id):
    return 'city is %s and user id is %s' % (city_id,user_id)


@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)


with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='JiangZhenfeng'))
    print(url_for('static_file'))
    print(url_for('hello'))
    print(url_for('add_numbers'))


def valid_login(username, password):
    return True


def log_the_user_in(username):
    return 'User %s login success!' % username


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=8009,debug=True)

